<?php

namespace App\Http\Controllers\Common;

use App\Models\User\User;

use Illuminate\Http\Request;

use App\Http\Controllers\Controller;

use Illuminate\Support\Facades\Redis as Redis;

class UserController extends Controller
{

    
    //登录页
    public function index (Request $request)
    {

        $redirect_url = $request->input('redirect_url');
        if (is_url($redirect_url)) {
            Redis::setex('WDH_LOGIN_REDIRECT_' . session_id(), 1800, $redirect_url);
        }

        return view('common/userLogin');

    }

    //登录操作
    public function login (Request $request) 
    {

        $login_name = $request->input('login_name');
        $password = $request->input('password');

        if ( empty($login_name) ) {
            return response()->json(['code' => 100001, 'message' => '登录账号不能为空']);
        }

        if ( empty($password)) {
            return response()->json(['code' => 100002, 'message' => '登录密码不能为空']);
        }

        if ( !isPwd($password)) {
            return response()->json(['code' => 100003, 'message' => '登录密码格式不正确']);
        }

        //查询用户是否存在
        $user = User::find($login_name);
        if (!$user) {
            return response()->json(['code' => 100004, 'message' => '该用户不存在']);
        }
        if ($user->userPwd != md5($password)) {
            return response()->json(['code' => 100005, 'message' => '用户密码不正确']);
        }

        //保存用户id到redis
        Redis::setex('WDH_ADMIN_USER_ID_' . session_id(), 86400, $user->userID);

        $redirect_url = Redis::get('WDH_LOGIN_REDIRECT_' . session_id());
        if (!$redirect_url) {
            $redirect_url = '/wap';
        }

        //添加登录日志
       /* $user_login = new UserOps;
        $user_login->user_id = $user_data['userID'];
        $user_login->ip = $request->ip();
        $user_login->op = 1;
        $user_login->extend_json = json_encode([
            'redirect_url' => $redirect_url,
            'session_id' => $session_id
        ]);
        $user_login->save();*/

        return response()->json(['code' => 200, 'message' => '登录成功', 'data' => ['redirect_url' => $redirect_url]]);

    }

    //退出
    public function logout(Request $request)
    {

        $redirect_url = $request->input('redirect_url');

        /*$userId = Redis::get('WDH_ADMIN_USER_ID_' . session_id());

        if ($userId) {
            //添加退出日志
            $user_login = new UserOps;
            $user_login->user_id = $userId;
            $user_login->ip = $request->ip();
            $user_login->op = 2;
            $user_login->extend_json = json_encode([
                'redirect_url' => $redirect_url,
                'session_id' => $session_id
            ]);
            $user_login->save();
        }*/

        Redis::del('WDH_ADMIN_USER_ID_' . session_id());

        header('Location: /lar/user/login?redirect_url=' . urlencode($redirect_url));

    }

}
